package com.cyy.media.service.impl;

import com.cyy.media.mapper.MediaFilesMapper;
import com.cyy.media.mapper.MediaProcessHistoryMapper;
import com.cyy.media.mapper.MediaProcessMapper;
import com.cyy.media.model.po.MediaFiles;
import com.cyy.media.model.po.MediaProcess;
import com.cyy.media.model.po.MediaProcessHistory;
import com.cyy.media.service.MediaFileProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author cyy
 * @date 2025/2/11
 * @description MediaFileProcessServiceImpl
 */
@Slf4j
@Service
public class MediaFileProcessServiceImpl implements MediaFileProcessService {

    @Autowired
    MediaProcessMapper mediaProcessMapper;

    @Autowired
    MediaFilesMapper mediaFilesMapper;

    @Autowired
    MediaProcessHistoryMapper mediaProcessHistoryMapper;

    @Override
    public List<MediaProcess> getMediaProcessList(int sharedIndex, int sharedTotal, int count) {
        return mediaProcessMapper.selectListBySharedIndex(sharedTotal, sharedIndex, count);
    }

    @Override
    public boolean startTask(long id) {
        int res = mediaProcessMapper.startTask(id);
        return res > 0;
    }

    @Override
    public void saveProcessFinishStatus(Long taskId, String status, String fileId, String url, String errMsg) {
        MediaProcess mediaProcess = mediaProcessMapper.selectById(taskId);
        if(mediaProcess == null){
            return;
        }
        //任务执行失败
        if(status.equals("3")){
            mediaProcess.setStatus("3");
            mediaProcess.setFailCount(mediaProcess.getFailCount()+1);
            mediaProcess.setErrormsg(errMsg);
            mediaProcessMapper.updateById(mediaProcess);
            return;
        }
        //成功
        //更新media_file的url
        MediaFiles mediaFiles = mediaFilesMapper.selectById(fileId);
        mediaFiles.setUrl(url);
        mediaFilesMapper.updateById(mediaFiles);
        //更新mediaProcess的状态，
        mediaProcess.setStatus("2");
        mediaProcess.setFinishDate(LocalDateTime.now());
        mediaProcess.setUrl(url);
        mediaProcessMapper.updateById(mediaProcess);
        // 插入历史表，从当前表中删除任务
        MediaProcessHistory mediaProcessHistory = new MediaProcessHistory();
        BeanUtils.copyProperties(mediaProcess, mediaProcessHistory);
        mediaProcessHistoryMapper.insert(mediaProcessHistory);
        mediaProcessMapper.deleteById(mediaProcess.getId());

    }
}
